<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>colorfulBall</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    canvas {
      border: 1px solid red;
    }
  </style>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script>
  let canvas = document.querySelector('#canvas');
  canvas.height = innerHeight;
  canvas.width = innerWidth;
  let ctx = canvas.getContext('2d');

  const ballsArr = [];

  class Ball {
    constructor(x, y, arr) {
      this.x = x; // x轴位置
      this.y = y; // y轴位置
      this.r = 30;
      this.color = `rgba(${Math.random() * 256},${Math.random() * 256},${Math.random() * 256})`;
      this.dx = parseInt(Math.random() * 18) - 9;
      this.dy = parseInt(Math.random() * 18) - 9;
      arr.push(this)
    }

    render() {
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, true);
      ctx.closePath();
      ctx.fillStyle = this.color;
      ctx.fill()
    }

    update() {
      this.x += this.dx;
      this.y += this.dy;
      this.r--;
    }

    gpDie(arr) {
      arr.forEach((item, index) => {
        if (item.r < 1) {
          arr.splice(index, 1)
        }
      })
    }
  }


  setInterval(() => {
    ctx.clearRect(0, 0, innerWidth, innerHeight);
    ballsArr.forEach(item => {
      item.update();
      item.gpDie(ballsArr);
      item && item.render()
    })
  }, 1000 / 60);

  canvas.onmousemove = (event) => {
    new Ball(event.clientX, event.clientY, ballsArr)
  }

</script>
</html>
